package com.yanx.system.web.query;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.yanx.common.command.Executor;
import com.yanx.common.core.command.PageQryCommand;
import com.yanx.common.security.SecurityUtils;
import com.yanx.common.utils.String_;
import com.yanx.system.base.domain.entity.QSysMenu;
import com.yanx.system.base.domain.entity.SysUser;
import com.yanx.system.base.domain.entity.rel.QSysRoleMenu;
import com.yanx.system.base.domain.entity.rel.QSysUserRole;
import com.yanx.system.base.model.qo.SysMenuQo;
import com.yanx.system.base.model.vo.SysMenuVo;
import com.yanx.system.base.query.SysMenuByIdQry;
import lombok.AllArgsConstructor;

import java.util.List;

/**
 * 菜单权限分页查询
 *
 * @author: gotanks
 * @create: 2023-2-9
 */
@AllArgsConstructor
public class SysMenuListByUserIdQry extends PageQryCommand<List<SysMenuVo>> {

    private SysMenuQo sysMenuQo;

    @Override
    public List<SysMenuVo> execute(Executor executor) {
        QSysMenu sysMenu = QSysMenu.sysMenu;
        QSysRoleMenu sysRoleMenu = QSysRoleMenu.sysRoleMenu;
        QSysUserRole sysUserRole = QSysUserRole.sysUserRole;

        //查询条件
        BooleanBuilder condition = new BooleanBuilder();
        condition.and(sysMenu.deleted.eq(false));
        if (sysMenuQo != null) {
            //自定义查询条件
            if (String_.isNotBlank(sysMenuQo.getMenuName())) {
                condition.and(sysMenu.menuName.contains(sysMenuQo.getMenuName()));
            }
            if (String_.isNotBlank(sysMenuQo.getStatus())) {
                condition.and(sysMenu.status.eq(sysMenuQo.getStatus()));
            }
            if (String_.isNotBlank(sysMenuQo.getVisible())) {
                condition.and(sysMenu.visible.eq(sysMenuQo.getVisible()));
            }
        }
        Long userId = SecurityUtils.getLoginUser().getUserId();
        if (SysUser.isAdmin(userId)) {
            JPAQuery<SysMenuVo> query = queryFactory.select(SysMenuByIdQry.fields())
                    .from(sysMenu)
                    .where(condition)
                    .orderBy(sysMenu.parentId.asc(), sysMenu.orderNum.asc());
            return this.pageList(query);
        } else {
            JPAQuery<SysMenuVo> query = queryFactory.select(SysMenuByIdQry.fields())
                    .from(sysMenu)
                    .leftJoin(sysRoleMenu).on(sysRoleMenu.menuId.eq(sysMenu.id))
                    .leftJoin(sysUserRole).on(sysUserRole.roleId.eq(sysRoleMenu.roleId))
                    .where(condition, sysUserRole.userId.eq(userId))
                    .orderBy(sysMenu.parentId.asc(), sysMenu.orderNum.asc());
            return this.pageList(query);
        }

    }

}